import http from '../utils/http'

// 用户文件相关 API

export const getUserFiles = (userId) =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}`)

export const getUserFilesInDirectory = (userId, directory = '/home/coder/project') =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/directory`, { params: { directory } })

export const getUserProjects = (userId) =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/projects`)

export const getFileContent = (userId, filePath) =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/file`, { params: { filePath } })

export const searchUserFiles = (userId, query, searchType = 'name') =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/search`, { params: { query, searchType } })

export const uploadFileToIde = (userId, file, targetDirectory = '/home/coder/project') => {
	const formData = new FormData()
	formData.append('file', file)
	formData.append('targetDirectory', targetDirectory)
	return http.post(`/api/user-files/${encodeURIComponent(userId)}/upload`, formData, {
		headers: { 'Content-Type': 'multipart/form-data' },
	})
}

export const uploadFilesToIde = (userId, files, targetDirectory = '/home/coder/project') => {
	const formData = new FormData()
	files.forEach((f) => formData.append('files', f))
	formData.append('targetDirectory', targetDirectory)
	return http.post(`/api/user-files/${encodeURIComponent(userId)}/upload/batch`, formData, {
		headers: { 'Content-Type': 'multipart/form-data' },
	})
}

export const getUserFileTree = (userId, rootDirectory = '/home/coder/project') =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/tree`, { params: { rootDirectory } })

export const getUserFileStats = (userId) =>
	http.get(`/api/user-files/${encodeURIComponent(userId)}/stats`)

export const saveFile = (userId, filePath, content) =>
	http.post(`/api/user-files/${encodeURIComponent(userId)}/save`, content, {
		headers: { 'Content-Type': 'text/plain;charset=UTF-8' },
		params: { filePath },
	})

export const createFile = (userId, filePath) =>
	http.post(`/api/user-files/${encodeURIComponent(userId)}/create-file`, null, { params: { filePath } })

export const createDirectory = (userId, dirPath) =>
	http.post(`/api/user-files/${encodeURIComponent(userId)}/create-directory`, null, { params: { dirPath } })

export const deletePath = (userId, path, recursive = true) =>
	http.delete(`/api/user-files/${encodeURIComponent(userId)}/delete`, { params: { path, recursive } })